/*
* 设置
* */
function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}

var times = 66;
var genRate = 66;
var timer = setInterval(function(){
	genRate--
	times--
	if(times <=29){
		clearInterval(timer)
	}
},1000);
var $canvans = $('#stage');
var VW = window.innerWidth;
var VH = window.innerHeight;
$canvans.attr('width', VW);
$canvans.attr('height', VH);
var token = getQueryString('token');
// token = 'QBeXrkby';
/*
* 飞船
* */
function Ship(ctx){
  // 加载图片
	gameMonitor.im.loadImage(['/nati/static/img/player.png']);
  // 飞船大小
	this.width = 50;
	this.height = 86;
  // 飞创初始位置
	this.left = gameMonitor.w/2 - this.width/2; // 居中
	this.top = gameMonitor.h - 2*this.height; // 距离底部 1 身位
  // 创建图片
	this.player = gameMonitor.im.createImage('/nati/static/img/player.png');
	// 绘制
	this.paint = function(){
		ctx.drawImage(this.player, this.left, this.top, this.width, this.height);
	};
	// 设置位置
	this.setPosition = function(event){
    /* 获取移动坐标 */
    var tarL = '',tarT = '';
		if(gameMonitor.isMobile()){
			tarL = event.changedTouches[0].clientX;
			tarT = event.changedTouches[0].clientY;
		}
		else{
			tarL = event.offsetX;
			tarT = event.offsetY;
		}
    // 设置坐标
		this.left = tarL - this.width/2; // -16 为预留出手指位置方便用户查看
		this.top = tarT - this.height;
    // 最左边
		if(this.left<0){
			this.left = 0;
		}
    // 最右边
		if(this.left>gameMonitor.w-this.width){
			this.left = gameMonitor.w-this.width;
		}
    // 最上边
		if(this.top<0){
			this.top = 0;
		}
    // 最下边
		if(this.top>gameMonitor.h - this.height){
			this.top = gameMonitor.h - this.height;
		}
    // 绘制
		this.paint();
	};
	// 控制
	this.controll = function(){
		var _this = this;
		var stage = $('#gamepanel');
		var currentX = this.left,
			currentY = this.top,
			move = false;
		stage.on(gameMonitor.eventType.start, function(event){
			_this.setPosition(event);
			move = true;
		}).on(gameMonitor.eventType.end, function(){
			move = false;
		}).on(gameMonitor.eventType.move, function(event){
			event.preventDefault();
			if(move){
				_this.setPosition(event);	
			}
		});
	};
	// 吃月饼
	this.eat = function(foodlist){
		for(var i=foodlist.length-1; i>=0; i--){
			var f = foodlist[i];
			// console.log(f)
      // console.log(foodlist[i].top, foodlist[i].height)
			if(f){
        /*var l1 = this.top+this.height/2 - (f.top+f.height/2);
        var l2 = this.left+this.width/2 - (f.left+f.width/2);
        var l3 = Math.sqrt(l1*l1 + l2*l2);

        if(l3<=this.height/2 + f.height/2){
        */
        var l1 = this.top+this.height/2 - (f.top+f.height/2);
        var l2 = this.left+this.width/2 - (f.left+f.width/2);
        var l3 = Math.sqrt(l1*l1 + l2*l2);
        // console.log(Math.abs(l1 - (this.height/2 + f.height/2))<=0);
				if( Math.abs(l1) - (this.height/2 + f.height/2)<=0 && Math.abs(l2) - (this.width/2 + f.width/2)<=0 ){

					foodlist[f.id] = null;
					// 2
					// f.type 毒月饼
					// console.log(gameMonitor)
					if(f.type==0){
						console.log('游戏失败');
            ai.ajax({
              url: '/midautumn/endGame',
              urlType: 'games',
              withToken: token,
							origin: true,
							parse: true,
            }, function(res) {
              console.log(res);
              gameMonitor.luck_times = res.data.luck_times;
            });
						gameMonitor.stop(); // 暂停游戏
						$('#gameoverPanel').show(); // GameOver
						// 2 秒后隐藏 GameOver
						setTimeout(function(){
							$('#gameoverPanel').hide();
							// 显示重新开始
							$('#resultPanel').show();
							gameMonitor.getScore();
						}, 2000);
					}
					// score 好月饼
					else{
						$('#score').text(++gameMonitor.score);
						// 心跳动的动画
						$('.heart').removeClass('hearthot').addClass('hearthot');
						setTimeout(function() {
							$('.heart').removeClass('hearthot')
						}, 200);
            ai.ajax({
              url: '/midautumn/addIntegral',
              urlType: 'games',
              withToken: token,
              origin: true,
              parse: true,
            }, function(res) {
              console.log(res);
            });
					}
				}
			}
		}
	}
}

var carType = [

];
function carSet(obj, set) {
  obj.width = set.width;
  obj.height = set.height;
  obj.left = set.left;
  obj.top = set.top;
}

/* 月饼 */
function Food(type, left, id, car){
	this.speedUpTime = 300; // 速度提升倍率
	this.id = id;
	this.type = type; // 月饼类型
	var pic = '';
	if(this.type){
		// 星星
    this.width = 40;
    this.height = 40;
    this.left = left;
    this.top = -20;
	}else{
		// 汽车
    /*obj.width = 47;
    obj.height = 90;
    obj.left = left;
    obj.top = -45;*/
		// console.log(car)
		switch (car) {
      case 0:
        carSet(this, {
          width: 44, height: 85, left: left, top: -170
        });
        pic = '/nati/static/img/car1.png';
        break;
      case 1:
        carSet(this, {
          width: 40, height: 90, left: left, top: -180
        });
        pic = '/nati/static/img/car2.png';
        break;
      case 2:
        carSet(this, {
          width: 40, height: 88, left: left, top: -176
        });
        pic = '/nati/static/img/car3.png';
        break;
      case 3:
        carSet(this, {
          width: 42, height: 123, left: left, top: -246
        });
        pic = '/nati/static/img/car4.png';
        break;
      case 4:
        carSet(this, {
          width: 42, height: 123, left: left, top: -246
        });
        pic = '/nati/static/img/car5.png';
        break;
		}
	}
	this.speed = 0.04 * Math.pow(1.2, Math.floor(gameMonitor.time/this.speedUpTime));
	this.loop = 0;
	// 创建图片
	var p = this.type == 0 ? pic : '/nati/static/img/food2.png';
	this.pic = gameMonitor.im.createImage(p);
}
/* 绘制 */
Food.prototype.paint = function(ctx){
	ctx.drawImage(this.pic, this.left, this.top, this.width, this.height);
};
/* 移动 */
Food.prototype.move = function(ctx){
	if(gameMonitor.time % this.speedUpTime == 0){
		this.speed *= 1.2;
	}
	this.top += ++this.loop * this.speed;
	if(this.top>gameMonitor.h){
	 	gameMonitor.foodList[this.id] = null;
	}
	else{
		this.paint(ctx);
	}
};
/* 图片控制 */
function ImageMonitor(){
	var imgArray = [];
	return {
		createImage : function(src){
			return typeof imgArray[src] != 'undefined' ? imgArray[src] : (imgArray[src] = new Image(), imgArray[src].src = src, imgArray[src])
		},
		loadImage : function(arr, callback){
			for(var i=0,l=arr.length; i<l; i++){
				var img = arr[i];
				imgArray[img] = new Image();
				imgArray[img].onload = function(){
					if(i==l-1 && typeof callback=='function'){
						callback();
					}
				};
				imgArray[img].src = img
			}
		}
	}
}
ai.ajax({
  url: '/midautumn/gameIndex',
  urlType: 'games',
  withToken: token,
	origin: true,
	parse: true,
}, function(res) {
  console.log(res);
  // 用户游戏次数
  gameMonitor.remaining = res.data.game_times;
	// 用户可以抽奖的次数
  gameMonitor.reward = res.data.luck_times;
  // 月饼数量
  gameMonitor.score = res.data.number;
  $('#score').text(gameMonitor.score);
  // 初始化游戏
  gameMonitor.init();
  // 次数用尽
	if(gameMonitor.remaining <= 0){
    var popup = $('.popup');
    popup.find('p').text('游戏挑战次数用完啦~ 持续关注康侣公众号，会有更多惊喜哦~');
    var a = popup.find('a');
    if(res.data.luck_times<=0){
      a.text('去论坛逛逛');
      a.attr('href', 'https://wechat.jkbanlv.com/getcode/home');
      a.on('click',function(e){
        popup.hide();
      });
		}else{
      a.text('去抽奖');
      a.attr('href', '/rotate?token=' + token);
      a.on('click',function(e){
        popup.hide();
      });
		}
    popup.show();
	}
});
/* 游戏控制 */
var gameMonitor = {
  remaining : 0,  // 次数
  integral_id : -1,  // id
  reward: 0,  // 奖励次数
  prize_number: 0,
	luck_times: 0,
  w : VW,
	h : VH,
	bgWidth : VW,
	bgHeight : VW * 3.51875,
	time : 0,	// 游戏时间
	timmer : null,
	bgSpeed : 6,
	bgloop : 0,
	shadowSpeed : 6,
	shadowWidth : 0,
	shadowHeight : 0,
  shadowWidth2 : 0,
  shadowHeight2 : 0,
	rollShadow :1,
  rollNext: 2,
	score : '',
	im : new ImageMonitor(),
	foodList : [],
	bgDistance : 100,//背景位置
	eventType : {
		start : 'touchstart',
		move : 'touchmove',
		end : 'touchend'
	},
	init : function(){
		var _this = this;
		var canvas = document.getElementById('stage');
		var ctx = canvas.getContext('2d');

		//绘制背景
		var bg = new Image();
		_this.bg = bg;

    bg.onload = function(){
      ctx.drawImage(bg, 0, 0, _this.bgWidth, _this.bgHeight);
    };
    bg.src = '/nati/static/img/bg.jpg';

		//绘制阴影
		// shadow92-288 shadow156-70 shadow181-145 shadow211-94
		var shadows = new Image();
		_this.shadows = shadows;
		_this.shadowWidth = 92;
		_this.shadowHeight = 288;
		_this.shadowArray = [
      { src: '/nati/static/img/shadow92-288.png', width: 92, height: 288 },
      { src: '/nati/static/img/shadow156-310.png', width: 156, height: 310 },
      { src: '/nati/static/img/shadow181-653.png', width: 181, height: 653 },
      { src: '/nati/static/img/shadow211-94.png', width: 211, height: 94 },
		];
    /*shadows.onload = function(){
      ctx.drawImage(shadows, (VW - _this.shadowWidth), 0, _this.shadowWidth, _this.shadowHeight);
    };
    shadows.src = 'static/img/shadow92-288.png';

    var shadows2 = new Image();
    _this.shadows2 = shadows2;
    _this.shadowWidth2 = 156;
    _this.shadowHeight2 = 310;*/
    /*shadows2.onload = function(){
      ctx.drawImage(shadows2, (VW - _this.shadowWidth2), 0, _this.shadowWidth2, _this.shadowHeight2);
    };
    shadows2.src = 'static/img/shadow211-94.png';*/


		_this.initListener(ctx);
	},
	initListener : function(ctx){
		var _this = this;
		var body = $(document.body);
		$(document).on(gameMonitor.eventType.move, function(event){
			event.preventDefault();
		});
		// 重新开始
		body.on(gameMonitor.eventType.start, '.replay, .playagain', function(){
			// console.log('继续挑战');
      ai.ajax({
        url: '/midautumn/startGame',
        urlType: 'games',
        withToken: token,
        origin: true,
        parse: true,
      }, function(res) {
        // console.log(res);
        // 机会 == 0
        if(gameMonitor.remaining <= 0 || res.data.code === 500) {
          return;
        }
        // 计数
        --gameMonitor.remaining;
        $('#resultPanel').hide();
        var canvas = document.getElementById('stage');
        var ctx = canvas.getContext('2d');
        _this.ship = new Ship(ctx);
        _this.ship.controll();
        /* 如果月饼数量 跟奖励次数不对应 则需要调整 */
        _this.reset(res.data.number);
        _this.run(ctx);
      });
		});
		body.on(gameMonitor.eventType.start, '#frontpage', function(){
			$('#frontpage').css('left', '-100%');
		});
		// 开始游戏
		body.on(gameMonitor.eventType.start, '#guidePanel', function(){
			// console.log('游戏开始');
			// 减少一次机会
      if(gameMonitor.remaining <= 0) {
        var popup = $('.popup');
        popup.find('p').text(res.message);
        var a = popup.find('a');
        a.hide();
        /*a.text('去论坛逛逛');
        a.attr('href', 'https://wechatlt.jkbanlv.com');*/
        popup.on('click',function(e){
          popup.hide();
        });
        popup.show();
        return;
      };
      --gameMonitor.remaining;
      ai.ajax({
				url: '/midautumn/startGame',
				urlType: 'games',
				withToken: token,
				origin: true,
				parse: true,
			}, function(res) {
				// console.log(res);
				if(res.code === 500){
          var popup = $('.popup');
          popup.find('p').text(res.message);
          var a = popup.find('a');
          a.hide();
          /*a.text('去论坛逛逛');
          a.attr('href', 'https://wechatlt.jkbanlv.com');*/
          popup.on('click',function(e){
            popup.hide();
          });
          popup.show();
				}
			});
			$(this).hide();
			_this.ship = new Ship(ctx);
			_this.ship.paint();
			_this.ship.controll();
			gameMonitor.run(ctx);
		});
		// 抽奖
    body.on(gameMonitor.eventType.start, '.share', function(){
    	// 设置数值
			/*ai.ajax({
				url: '/midautumn/drawList',
        urlType: 'games',
        withToken: 'games',
        origin: true,
        parse: true,
			},function(res){
				console.log(res)
			});*/
      var popup = $('.popup');
			// $('.mask').show();
			/*setTimeout(function(){
				$('.mask').hide();
			},300)*/
			if(gameMonitor.reward > 0){
				// console.log(123);
				window.location.href= '/rotate?reward=' + gameMonitor.reward + '&token=' + token;
        /*$('.weixin-share').show().on(gameMonitor.eventType.start, function(){
          // console.log('隐藏');
          // $(this).hide();
        });*/
			}else if(gameMonitor.remaining > 0){
				popup.find('p').text('再去挑战一下，高分可以获得更多抽奖机会哦~');
				var a = popup.find('a');
        a.text('确定');
        a.attr('href', 'javascript:;');
        a.on('click',function(e){
          popup.hide();
				});
        popup.show();
			}else{
				popup.find('p').text('抽奖次数已经用完了~ 持续关注康侣公众号，会有更多惊喜哦~');
        var a = popup.find('a');
        a.text('去论坛逛逛');
        a.attr('href', 'https://wechat.jkbanlv.com/getcode/home');
        a.on('click',function(e){
          popup.hide();
        });
        popup.show();
			}
    });

		/*WeixinApi.ready(function(Api) {
            // 微信分享的数据
            //分享给好友的数据
            var wxData = {
                "appId": "",
                "imgUrl" : "static/img/icon.png",
                "link" : "http://dev.360.cn/html/zhuanti/yutu.html",
                "desc" : "进击的玉兔",
                "title" : "“玩玉兔 抢月饼”"
            };

            //朋友圈数据
            var wxDataPyq ={
            	"appId": "",
                "imgUrl" : "static/img/icon.png",
                "link" : "http://dev.360.cn/html/zhuanti/yutu.html",
                "desc" : "“玩玉兔 抢月饼”",
                "title" : "进击的玉兔"
            }

            // 分享的回调
            var wxCallbacks = {
                // 分享操作开始之前
                ready : function() {},
                cancel : function(resp) {},
                fail : function(resp) {},
                confirm : function(resp) {},
                all : function(resp) {
                    //location.href=location.href
                }
            };

            // 用户点开右上角popup菜单后，点击分享给好友，会执行下面这个代码
            Api.shareToFriend(wxData, wxCallbacks);
            // 点击分享到朋友圈，会执行下面这个代码
            Api.shareToTimeline(wxDataPyq, wxCallbacks);
            // 点击分享到腾讯微博，会执行下面这个代码
            Api.shareToWeibo(wxData, wxCallbacks);
        });*/

	},
	rollBg : function(ctx){
		if(this.bgDistance>=this.bgHeight){
			this.bgloop = 0;
			this.rollShadow++;
			this.rollNext++;
      // console.log(this.rollShadow%4);
			// 重新绘制
     /* this.shadows.src = this.shadowArray[this.rollShadow%4].src;
      this.shadowWidth = this.shadowArray[this.rollShadow%4].width;
      this.shadowHeight = this.shadowArray[this.rollShadow%4].height;*/
			// next
      /*this.shadows2.src = this.shadowArray[this.rollNext%4].src;
      this.shadowWidth2 = this.shadowArray[this.rollNext%4].width;
      this.shadowHeight2 = this.shadowArray[this.rollNext%4].height;*/
		}
		this.bgDistance = ++this.bgloop * this.bgSpeed;
		// this.showDistance = ++this.bgloop * this.bgSpeed;
    ctx.drawImage(this.bg, 0, this.bgDistance-this.bgHeight, this.bgWidth, this.bgHeight);
		ctx.drawImage(this.bg, 0, this.bgDistance, this.bgWidth, this.bgHeight);

    /*ctx.drawImage(this.shadows2, (VW - this.shadowWidth2), this.showDistance-this.bgHeight, this.shadowWidth2, this.shadowHeight2);
    ctx.drawImage(this.shadows, (VW - this.shadowWidth), this.showDistance, this.shadowWidth, this.shadowHeight);*/
	},
	run : function(ctx){
		var _this = gameMonitor;
		ctx.clearRect(0, 0, _this.bgWidth, _this.bgHeight);
		_this.rollBg(ctx);

		//绘制飞船
		_this.ship.paint();
		_this.ship.eat(_this.foodList);

		//产生月饼
		_this.genorateFood();

		//绘制月饼
		for(i=_this.foodList.length-1; i>=0; i--){
			var f = _this.foodList[i];
			if(f){
				f.paint(ctx);
				f.move(ctx);
			}
		}
		_this.timmer = setTimeout(function(){
			gameMonitor.run(ctx);
		}, Math.round(1000/60));

		_this.time++;
	},
	stop : function(){
		var _this = this;
		$('#stage').off(gameMonitor.eventType.start + ' ' +gameMonitor.eventType.move);
		setTimeout(function(){
			clearTimeout(_this.timmer);
		}, 0);
	},
	genorateFood : function(){
		// var genRate = 100; //产生月饼的频率
		var random = Math.random();
		if(random*genRate>genRate-1){
      // console.log(genRate)
			var left = Math.random()*(this.w - 50);
			/* 取范围宽度值 */
			// 0.84 为去除两边马路牙子的宽度  0.08 为单边马路牙子
			var lines = 4; // 4 条马路
			var SW = this.w * 0.84;
			var unit = SW / lines;
			var aside = this.w * 0.08;
			var startArray = [];
			// 获取范围值
			for(var i=0; i<lines; i+= 1){
        startArray[i] = {
        	start: Math.round(unit * i + aside),
					end: Math.round(unit * (i+1) + aside)
				}
			}
			var type = Math.floor(left)%2 == 0 ? 0 : 1;
			// 汽车
			if(!type){
				var rand = Math.round(Math.random()*3);
				var temp = randomFrom(startArray[rand].start, startArray[rand].end);
				left = temp;
				// console.log(left)
			}
			// console.log(rand);
			var car = Math.round(Math.random()*4);
			var id = this.foodList.length;
			var f = new Food(type, left, id, car);
			this.foodList.push(f);
		}
	},
	reset : function(yuebing){
		this.foodList = [];
		this.bgloop = 0;
		this.score = yuebing;
		this.timmer = null;
		this.time = 0;
		$('#score').text(this.score);
	},
	getScore : function(){
		var time = Math.floor(this.time/60);
		var score = this.score;
		var user = 1;
		if(score==0){
			$('#scorecontent').html('真遗憾，您竟然<span class="lighttext">一个</span>星星都没有抢到！');
      if(gameMonitor.remaining <= 0) {
        $('.btn2').text('今日挑战次数用尽').removeClass('share').addClass('playagain');
      }else{
        $('.btn2').text('继续挑战(剩余'+gameMonitor.remaining + '次)').removeClass('share').addClass('playagain');
      }
      $('.btn1').text('立即开始抽奖').removeClass('playagain').addClass('share');
			$('#fenghao').removeClass('geili yinhen').addClass('yinhen');
			return;
		}
		else{
			user = this.luck_times;
			gameMonitor.reward = this.luck_times;
		}
		if(user==0){
      $('#scorecontent').html('您今天一共抢到了<span id="sscore" class="lighttext">21341</span>个星星<br>真可惜，要<span id="suser" class="lighttext">30个</span>星星才能获得一次抽奖机会！');
      $('#stime').text(time);
      $('#sscore').text(score);
      if(gameMonitor.remaining <= 0) {
        $('.btn2').text('今日挑战次数用尽').removeClass('share').addClass('playagain');
      }else{
        $('.btn2').text('继续挑战(剩余'+gameMonitor.remaining + '次)').removeClass('share').addClass('playagain');
      }
      $('.btn1').text('立即开始抽奖').removeClass('playagain').addClass('share');
      $('#fenghao').removeClass('geili yinhen').addClass('yinhen');
      return;
		}
		$('#fenghao').removeClass('geili yinhen').addClass('geili');
		$('#scorecontent').html('您今天一共抢到了<span id="sscore" class="lighttext">21341</span>个星星<br>累计获得了<span id="suser" class="lighttext"></span>次抽奖机会！');
		$('#stime').text(time);
		$('#sscore').text(score);
		$('#suser').text(user);
    if(gameMonitor.remaining <= 0) {
      $('.btn2').text('今日挑战次数用尽').removeClass('share').addClass('playagain');
    }else{
      $('.btn2').text('继续挑战(剩余'+gameMonitor.remaining + '次)').removeClass('share').addClass('playagain');
    }
    $('.btn1').text('立即开始抽奖').removeClass('playagain').addClass('share');
	},
	isMobile : function(){
		var sUserAgent= navigator.userAgent.toLowerCase(),
		bIsIpad= sUserAgent.match(/ipad/i) == "ipad",
		bIsIphoneOs= sUserAgent.match(/iphone os/i) == "iphone os",
		bIsMidp= sUserAgent.match(/midp/i) == "midp",
		bIsUc7= sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4",
		bIsUc= sUserAgent.match(/ucweb/i) == "ucweb",
		bIsAndroid= sUserAgent.match(/android/i) == "android",
		bIsCE= sUserAgent.match(/windows ce/i) == "windows ce",
		bIsWM= sUserAgent.match(/windows mobile/i) == "windows mobile",
		bIsWebview = sUserAgent.match(/webview/i) == "webview";
		return (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM);
     }
};
if(!gameMonitor.isMobile()){
	gameMonitor.eventType.start = 'mousedown';
	gameMonitor.eventType.move = 'mousemove';
	gameMonitor.eventType.end = 'mouseup';
}

function randomFrom(lowerValue,upperValue) {
  return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
}


